package com.cn.yugan.Activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;

import org.apache.http.Header;

import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.yugan.Cons.LoginConstants;
import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Engine.Http.Cookies;
import com.cn.yugan.Engine.Json.LoginJson;
import com.cn.yugan.mobile.R;
import com.cn.yugan.Utils.ImgUtils;
import com.cn.yugan.Utils.IntentUtils;
import com.cn.yugan.Utils.LogUtils;
import com.cn.yugan.Utils.StringConv;
import com.cn.yugan.Utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.UnsupportedEncodingException;


/**
 * Created by Rover on 2016/7/17 .
 * Email 357319517@qq.com
 * 登录成功-------->MainActivity(释放本活动)
 * 登录失败-------->提示错误(不释放本活动)
 * 注册------------>RegisterActivity(不释放本活动)
 * 忘记密码-------->ForgetAcativity(不释放本活动)
 */
public class LoginAcitivity extends AppCompatActivity implements View.OnClickListener {
    private Cookies cookies;
    private SharedPreferences sp;
    private EditText et_username, et_password, et_userlogin_capthca;
    private Button bt_login, bt_register, bt_forget;
    boolean isReLogin = false;                             //是否重新登录
    private int SERVER_FLAG = 0;                           //标记
    private Button bt_username_clear;
    private Button bt_pwd_clear;
    private TextWatcher username_watcher;
    private TextWatcher password_watcher;
    private ImageView yuganiang;
    private ImageView login_piccaptcha;
    private long mExitTime;
    private long clickme;
    public static LoginAcitivity instance = null;
   

    Handler mhander = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LoginConstants.LOGIN_ENABLE:
                    bt_login.setClickable(true);
                    break;
                case LoginConstants.LOGIN_UNABLE:
                    bt_login.setClickable(false);
                    break;
                case LoginConstants.PASS_ERROR:
                    Toast.makeText(LoginAcitivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    break;
                case LoginConstants.NAME_ERROR:
                    Toast.makeText(LoginAcitivity.this, "用户名错误", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //设置静态变量，方便关闭该activity
        instance = this;

        initActionbar();
        init();
        getcaptcha();
    }

    private void initActionbar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("登录");
    }

    private void init() {
        et_userlogin_capthca = (EditText) findViewById(R.id.et_userlogin_capthca);
        et_username = (EditText) findViewById(R.id.username);
        et_password = (EditText) findViewById(R.id.password);
        initWatcher();
        et_username.addTextChangedListener(username_watcher);
        et_password.addTextChangedListener(password_watcher);

        et_username.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        et_password.setImeOptions(EditorInfo.IME_ACTION_NONE);
        //回车改变焦点
        et_username.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    et_password.requestFocus();
                    return true;
                }
                return false;
            }
        });

        et_password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    return true;
                }
                return false;
            }
        });

        bt_login = (Button) findViewById(R.id.login);
        bt_register = (Button) findViewById(R.id.register);
        bt_forget = (Button) findViewById(R.id.forget);

        bt_login.setOnClickListener(this);
        bt_register.setOnClickListener(this);
        //注册功能未实现暂时不显示
        bt_register.setVisibility(View.INVISIBLE);
        bt_forget.setOnClickListener(this);
        //找回密码功能未实现暂时不显示
        bt_forget.setVisibility(View.INVISIBLE);
        bt_username_clear = (Button) findViewById(R.id.bt_username_clear);
        bt_pwd_clear = (Button) findViewById(R.id.bt_pwd_clear);

        bt_username_clear.setOnClickListener(this);
        bt_pwd_clear.setOnClickListener(this);

        yuganiang = (ImageView) findViewById(R.id.yuganniang);
        yuganiang.setOnClickListener(this);

        login_piccaptcha = (ImageView) findViewById(R.id.login_piccaptcha);
        login_piccaptcha.setOnClickListener(this);

        sp = getSharedPreferences("Session", MODE_PRIVATE);
    }

    /**
     * ET控件监控
     */

    private void initWatcher() {
        //用户名监控
        username_watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            //输入帐号，密码置空。et中有内容则清除按钮显示出来。
            public void afterTextChanged(Editable s) {
                et_password.setText("");
                if (s.toString().length() > 0) {
                    bt_username_clear.setVisibility(View.VISIBLE);
                } else {
                    bt_username_clear.setVisibility(View.INVISIBLE);
                }
            }
        };
        //密码监控
        password_watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    bt_pwd_clear.setVisibility(View.VISIBLE);
                } else {
                    bt_pwd_clear.setVisibility(View.INVISIBLE);
                }
            }
        };

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login: {
                if (et_username.getText().toString().equals("") && et_password.getText().toString().equals("")) {
                    ToastUtils.show(this, "你好过分！账号密码都是空的！！还想和我搭讪！！(╯▔皿▔)╯");
                } else if (et_username.getText().toString().equals("")) {
                    ToastUtils.show(this, "账号是空的还想调戏我？(╯▔皿▔)╯");
                    Toast.makeText(this, "账号是空的还想调戏我？(╯▔皿▔)╯", Toast.LENGTH_SHORT).show();
                } else if (et_password.getText().toString().equals("")) {
                    ToastUtils.show(this, "密码是空的还想调戏我？(╯▔皿▔)╯");
                } else {
                    login();
                }
                break;
            }
            case R.id.forget: {
//                //转到找回密码页面
//                Intent intent = new Intent(this, ForgetActivity.class);
//                //可能有传值，暂未定。
//                startActivity(intent);
                break;
            }
            case R.id.register: {
                //跳转到注册页面
//                Intent intent = new Intent(LoginAcitivity.this, RegisterActivity.class);
//                startActivity(intent);
                break;
            }
            case R.id.bt_username_clear: {
                et_username.setText("");
                break;
            }
            case R.id.bt_pwd_clear: {
                et_password.setText("");
                break;
            }
            case R.id.yuganniang:
                clickme++;
                if (clickme == 10) {
                    ToastUtils.show(this, "再点几次看看");
                } else if (clickme == 15) {
                    ToastUtils.show(this, "快了快了");
                } else if (clickme == 18) {
                    IntentUtils.startActivity(LoginAcitivity.this, high.class);
                }
                break;
            case R.id.login_piccaptcha:
                getcaptcha();
                break;
            default:
                break;
        }
    }

    //获取验证码
    private void getcaptcha() {
        String url = getString(R.string.serverurl) + getString(R.string.captcha);
        final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true,80,443);
        asyncHttpClient.get(url, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                ToastUtils.show(LoginAcitivity.this, "验证码获取失败");
                LogUtils.d(s);
            }
            
            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                String captchauri = getString(R.string.serverurl) + s;
                cookies = new Cookies(LoginAcitivity.this, headers);
                asyncHttpClient.get(captchauri, new BinaryHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        final Drawable drawable = ImgUtils.Bytes2Drawable(bytes);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                login_piccaptcha.setImageDrawable(drawable);
                            }
                        });
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        ToastUtils.show(LoginAcitivity.this, "验证码获取失败");
                        try {
                            LogUtils.d(new String(bytes, "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private void login() {
        //登录逻辑
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient(true, 80, 443);
        String url = getString(R.string.serverurl) + getString(R.string.login);
        final String username = et_username.getText().toString();
        final String password = et_password.getText().toString();
        final String captcha = et_userlogin_capthca.getText().toString();
        RequestParams params = new RequestParams();
        params.put("username", username);
        params.put("password", password);
        params.put("captcha", captcha);
        asyncHttpClient.addHeader("cookie", AddReqCookie.getLoginheader(LoginAcitivity.this));
        LogUtils.d("cookie=====>" + AddReqCookie.getLoginheader(LoginAcitivity.this));
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    LogUtils.d(new String(bytes, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                LoginJson lj = new LoginJson(bytes);
                if (lj.isSuccess()) {
                    LogUtils.d("username===>" + username);
                    LogUtils.d("password===>" + password);
                    LogUtils.d("captcha===>" + captcha);
                    sp = getSharedPreferences("Session", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("phone", username);
                    ToastUtils.show(LoginAcitivity.this, "登录成功！");
                    editor.commit();
                    try {
                        LogUtils.d(new String(bytes, "UTF-8"));
                        cookies.addcookie(headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    Intent intent = new Intent(LoginAcitivity.this, IndexActivity.class);
                    intent.putExtra("LoginMode", LoginConstants.LOGIN_NORMAL);
                    startActivity(intent);
                    LoginAcitivity.this.finish();
                } else {
                    LogUtils.d(lj.getDecs());
                    ToastUtils.show(LoginAcitivity.this, StringConv.Unicode2UTF8(lj.getDecs()));
                    getcaptcha();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                ToastUtils.show(LoginAcitivity.this, "网络状态或服务器异常");
                getcaptcha();
            }
        });
    }

    //双返回退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再次点击返回键退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_login_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_guestlogin:
                Toast.makeText(this, "游客登录只能看主页哦，鱼干娘就是这么任性(●ˇ∀ˇ●)", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginAcitivity.this, IndexActivity.class);
                intent.putExtra("LoginMode", LoginConstants.LOGIN_GUEST);
                startActivity(intent);
                LoginAcitivity.this.finish();
                break;
        }
        return true;
    }


}
